package org.example.netty.test.nio.netty.chat.handler;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import org.example.netty.test.nio.netty.chat.bean.PingMessage;
import org.example.netty.test.nio.netty.chat.bean.SystemMessage;
import org.example.netty.test.nio.netty.chat.bean.User;
import org.example.netty.test.nio.netty.chat.common.SystemMessageType;
import org.example.netty.test.nio.netty.chat.session.GlobalContent;
import org.example.netty.test.nio.netty.chat.session.UserSession;
import org.example.netty.test.nio.netty.chat.util.NettyChannelUtil;

/**
 * @author zp
 * @version 1.0
 * @description: 校验登入状态
 * @date 2023/4/10 20:01
 */
@Slf4j
public class VerificationLoginStatusHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        // 出现异常断开服务的状态 需要处理 session的旧数据

        Channel channel = ctx.channel();
        UserSession userSession = NettyChannelUtil.getUserSession(channel);
        if (userSession != null) {
            User user = userSession.getUser();
            log.error("客户端服务被异常断开了 用户ID：[{}] 用户名称：[{}]",user.getUserId(),user.getUserName());
            GlobalContent globalContent = GlobalContent.getInstance();
            // 解绑定
            globalContent.unbind(user.getUserId(), user.getUserName());
            // 删除channel里面的数据
            NettyChannelUtil.removeUserSession(channel);

        }else {
            log.error("客户端服务被异常断开了 用户未登入 无法显示名称");
        }

        super.exceptionCaught(ctx, cause);
    }

    /**
     * @description: 校验所有用户的登入状态
     * @author zp
     * @date: 2023/5/24 19:25
     * @param ctx
     * @param msg

     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if(msg instanceof PingMessage){
            // 如果是登入状态 可以向下传递Handler
            super.channelRead(ctx, msg);
        }else {
            GlobalContent instance = GlobalContent.getInstance();
            Channel channel = ctx.channel();
            User userServer = NettyChannelUtil.getUserServer(channel);
            // 登入的都会放到GlobalContent Map里面 所以直接判断GlobalContent里面有没有就可以
            if(userServer== null || instance.getSession(userServer.getUserName()) == null){
                // 发出报错信息
                SystemMessage.sendFailMessage(SystemMessageType.NO_LOGIN_USER_FAIL,ctx);
            }else {
                // 如果是登入状态 可以向下传递Handler
                super.channelRead(ctx, msg);
            }
        }

    }
}
